package com.itheima.aop;

import com.itheima.mapper.EmpLoginLogMapper;
import com.itheima.pojo.Emp;
import com.itheima.pojo.EmpLoginLog;
import com.itheima.pojo.LoginInfo;
import com.itheima.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Aspect
@Component
@Slf4j
public class EmpLoginLogAspect {
    @Autowired
    private EmpLoginLogMapper empLoginLogMapper;

    @Pointcut("execution(* com.itheima.controller.LoginController.login(..))")
    public void pc() {
    }

    @Around("pc()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        log.info("记录登录日志开始");
        EmpLoginLog empLoginLog = new EmpLoginLog();
        //登录时间
        empLoginLog.setLoginTime(LocalDateTime.now());
        Long start = System.currentTimeMillis();  //开始时间
        Object[] args = joinPoint.getArgs();
        Emp emp = (Emp) args[0];
        //设置用户名
        empLoginLog.setUsername(emp.getUsername());
        //设置密码
        empLoginLog.setPassword(emp.getPassword());
        Object result = null;
        try {
            //执行原始方法
            result = joinPoint.proceed();
            Result res = (Result) result;
            Integer isSuccess = res.getCode();
            //是否登录成功, 1:成功, 0:失败
            empLoginLog.setIsSuccess(isSuccess == 1 ? (short) 1 : (short) 0);
            LoginInfo loginInfo = (LoginInfo) res.getData();
            if (loginInfo != null) {
                String token = loginInfo.getToken();
                //设置token
                empLoginLog.setJwt(token);
            }
        } finally {
            //设置耗时
            empLoginLog.setCostTime(System.currentTimeMillis() - start);
            empLoginLogMapper.insert(empLoginLog);
        }
        log.info("记录操作日志结束");
        return result;
    }
}
